package com.authsystem.controller;

import com.authsystem.entity.User;
import com.authsystem.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/management")
    public String userManagement(HttpSession session,
                                 Model model,
                                 @RequestParam(required = false) String username,
                                 @RequestParam(required = false) String email,
                                 @RequestParam(required = false) Integer status,
                                 @RequestParam(required = false) String name,
                                 @RequestParam(required = false) String mobilephone,
                                 @RequestParam(required = false) Integer sex,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer pageSize) {

        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/";
        }

        List<User> users = userService.getUsersByCondition(username, email, status, name, mobilephone, sex, page, pageSize);
        Long totalCount = userService.countUsersByCondition(username, email, status, name, mobilephone, sex);
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        model.addAttribute("users", users);
        model.addAttribute("currentUser", user);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPages", totalPages);

        model.addAttribute("searchUsername", username);
        model.addAttribute("searchEmail", email);
        model.addAttribute("searchStatus", status);
        model.addAttribute("searchName", name);
        model.addAttribute("searchMobilephone", mobilephone);
        model.addAttribute("searchSex", sex);

        return "user-management";
    }

    @GetMapping("/profile")
    public String userProfile(HttpSession session, Model model) {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/";
        }

        User fullUser = userService.getUserWithRolesByUsername(user.getLoginname());
        model.addAttribute("user", fullUser);

        return "user-profile";
    }

    // 编辑用户页面
    @GetMapping("/edit/{id}")
    public String editUser(@PathVariable Long id, HttpSession session, Model model) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/";
        }

        // 这里应该查询用户详细信息，暂时用模拟数据
        User user = new User();
        user.setId(id);
        user.setLoginname("testuser");
        user.setName("测试用户");
        user.setEmail("test@example.com");
        user.setMobilephone("13800138000");
        user.setSex(1);
        user.setStatus(0);

        model.addAttribute("user", user);
        model.addAttribute("currentUser", currentUser);
        return "user-edit";
    }

    // 重置密码
    @PostMapping("/reset-password/{id}")
    public String resetPassword(@PathVariable Long id,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/";
        }

        // 这里应该调用Service重置密码，暂时模拟成功
        redirectAttributes.addFlashAttribute("success", "密码重置成功！新密码：123456");
        return "redirect:/user/management";
    }

    // 删除用户
    @PostMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id,
                             HttpSession session,
                             RedirectAttributes redirectAttributes) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/";
        }

        // 这里应该调用Service删除用户，暂时模拟成功
        redirectAttributes.addFlashAttribute("success", "用户删除成功！");
        return "redirect:/user/management";
    }

    // 新增用户页面
    @GetMapping("/add")
    public String addUser(HttpSession session, Model model) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/";
        }

        model.addAttribute("currentUser", currentUser);
        model.addAttribute("user", new User());
        return "user-edit";
    }
}